package netw;

import java.util.ArrayList;
import hypercast.I_LogicalAddress;
import ctrl.Control;

public class Users {
	private Control ctrl;
	private String name = "";
	private ArrayList<User> users = new ArrayList<User>();

	public Users(Control g) {
		ctrl = g;
	}
	
	public void start(){
		(new Thread(new Updater())).start();
	}

	public String getName() {
		return name;
	}

	public void setName(String s) {
		name = s;
	}

	public boolean broadcastMode() {
		return (ctrl.selUsers().length == 0 || ctrl.selUsers()[0] == 1 || ctrl
				.selUsers()[0] == 0);
	}

	public I_LogicalAddress getDestNode() {
		return users.get(ctrl.selUsers()[0] - 2).address;
	}

	public void advertise(long sl) {
		try {
			Thread.sleep(sl);
		} catch (InterruptedException e) {
			System.out.println("@Users - InterruptedException: " + e.getMessage());
		}
		ctrl.getNet().broadcastString(name, 4);
	}

	public void user(String name, I_LogicalAddress src) {
		if (ctrl.getNet().connected) {
			User temp = new User(name, src);
			int i = users.indexOf(temp);
			if (i >= 0) {
				users.get(i).alive = true;
			} else {
				ctrl.println(name + " arrived!");
				users.add(temp);
				ctrl.addUser(name);
			}
		}
	}

	public class User {
		public String name;
		public I_LogicalAddress address;
		boolean alive = true;

		public User(String n, I_LogicalAddress a) {
			name = n;
			address = a;
		}

		public boolean equals(Object obj) {
			return (obj.toString().equals(this.toString()));
		}

		public String toString() {
			return name + address.toString();
		}
	}

	private class Updater implements Runnable {
		public void run() {
			while (ctrl.getNet().connected) {
				for (int i = 0; i < 6 && ctrl.getNet().connected; i++)
					advertise(1000);
				for (int i = 0; i < users.size(); i++) {
					if (users.get(i).alive == false) {
						ctrl.println(users.get(i).name + " left the network.");
						users.remove(i);
						ctrl.remUser(i);
						i--;
					} else
						users.get(i).alive = false;
				}
			}
			for (; users.size() > 0;) {
				users.remove(0);
				ctrl.remUser(0);
			}
			
		}
	}
}
